package com.project.bookstore.book.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.bookstore.book.entity.BookIndex;
import com.project.bookstore.book.pojo.BookIndexVO;
import com.project.bookstore.book.pojo.BookMultiConditionVO;
import com.project.bookstore.book.entity.Book;
import com.project.bookstore.book.mapper.BookMapper;
import com.project.bookstore.book.pojo.BookDetailVO;
import com.project.bookstore.book.pojo.BookNameByKeyWordVO;
import com.project.bookstore.book.service.BookService;
import com.project.bookstore.category.service.CategoryService;
import com.project.bookstore.common.CommonResult;
import com.project.bookstore.exception.ServiceException;
import com.project.bookstore.exception.ServiceInternalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import static com.project.bookstore.common.State.*;

/**
 * @author 12603
 * @description 针对表【book】的数据库操作Service实现
 * @createDate 2022-04-17 17:06:34
 */
@Slf4j
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
        implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CategoryService categoryService;

    @Override
    public CommonResult<List<BookMultiConditionVO>> getByMultiCondition(BookMultiConditionVO multiConditionVO) {
        log.debug("多条件查询收到条件为：【{}】", multiConditionVO);
        return CommonResult.ok(bookMapper.multiConditionForAdmin(multiConditionVO));
    }

    @Override
    public int insert(BookDetailVO bookDetailVO) {
        return bookMapper.insertBook(bookDetailVO);
    }

    @Override
    public int deleteBookDetailById(Long id) {
        return bookMapper.deleteBookDetailById(id);
    }

    @Override
    public CommonResult<Void> updateBookDetailById(BookDetailVO bookDetailVO) {
        if (bookMapper.updateBookDetailById(bookDetailVO) != 1) {
            log.warn("未知原因根据ID更新书籍详情失败");
            throw new ServiceException(INTERNAL_EXCEPTION, "服务器忙请重试");
        }
        return CommonResult.ok();
    }

    @Override
    public BookDetailVO getBookDetailById(Long id) {
        BookDetailVO bookDetailById = bookMapper.getBookDetailById(id);
        if (bookDetailById == null) {
            log.warn("根据ID【{}】查找图书详情数据为空", id);
            throw new ServiceException(NOT_FOUND, "未找到该书籍");
        }
        log.debug("根据ID:{}查新到的图书详情:【{}】", id, bookDetailById);
        return bookDetailById;
    }

    public CommonResult<Void> multiDisEnableByIds(Long[] ids) {
        int r = bookMapper.updateIsEnable0ByIds(ids);
        if (r == 0) {
            log.debug("批量禁用没有影响");
            throw new ServiceException(INTERNAL_EXCEPTION, "服务器忙请重试");
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult<Void> multiEnableByIds(Long[] ids) {
        int r = bookMapper.updateIsEnable1ByIds(ids);
        if (r == 0) {
            log.debug("批量启用没有影响");
            throw new ServiceException(INTERNAL_EXCEPTION, "服务器忙请重试");
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult<Void> multiDisMarketableByIds(Long[] ids) {
        int r = bookMapper.updateIsMarketable0ByIds(ids);
        if (r == 0) {
            log.debug("批量禁止销售没有影响");
            throw new ServiceException(INTERNAL_EXCEPTION, "服务器忙请重试");
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult<Void> multiMarketableByIds(Long[] ids) {
        int r = bookMapper.updateIsMarketable1ByIds(ids);
        if (r == 0) {
            log.debug("批量开启销售没有影响");
            throw new ServiceException(INTERNAL_EXCEPTION, "服务器忙请重试");
        }
        return CommonResult.ok();

    }

    @Override
    public BookDetailVO getByBookName(String bookName) {
        return bookMapper.selectByBookName(bookName);
    }

    @Override
    public boolean hasPCS(Map<Long, Integer> bookPCSMap) {
        ArrayList<Long> bookIds = new ArrayList<>(bookPCSMap.keySet());
        System.out.println("bookIds = " + bookIds);
        Integer[] countsDB = bookMapper.selectCountById(bookIds);
        System.out.println("countsDB = " + Arrays.toString(countsDB));
        Integer[] counts = bookPCSMap.values().toArray(new Integer[0]);
        System.out.println("counts = " + Arrays.toString(counts));
        if (counts.length != countsDB.length) {
            log.warn("数据库找到数据条数【{}】不等于查找条数【{}】", countsDB, counts);
            return false;
        }
        for (int i = 0; i < countsDB.length; i++) {
            if (counts[i] > countsDB[i]) {
                log.warn("图书ID【{}】的库存为【{}】不足订单需求【{}】",
                        bookIds.get(i), countsDB[i], counts[i]);
                return false;
            }
        }
        return true;
    }

    @Override
    public CommonResult<List<BookIndexVO>> getBooksByClassifyIdByParentId(Long parentId) {
        Long[] classifyIds = categoryService.getRelatedClassifyIds(parentId);
        if (classifyIds.length == 0) {
            log.debug("父ID【{}】的子ID为空", parentId);
            return null;
        }
        List<BookIndexVO> bookIndexVOS = bookMapper.listBookByCategoryIds(classifyIds);
        if (bookIndexVOS==null){
            log.warn("通过IDS【{}】查到的数据为空",classifyIds);
            return null;
        }
        return CommonResult.ok(bookIndexVOS);
    }

    @Override
    public CommonResult<List<BookIndexVO>> getBooksByClassifyId(Long categoryId) {
        List<BookIndexVO> bookIndexVOS = bookMapper.listBookByCategoryId(categoryId);
        if (bookIndexVOS == null) {
            log.warn("根据类别ID获取数据时发生未知错误");
            throw new ServiceInternalException();
        }
        return CommonResult.ok(bookIndexVOS);
    }

    @Override
    public CommonResult<List<BookIndexVO>> getBooksForIndex() {
        List<BookIndexVO> bookIndexVOS = bookMapper.selectForIndex();
        if (bookIndexVOS == null) {
            log.warn("首页书籍展示数据为空");
            throw new ServiceInternalException();
        }
        return CommonResult.ok(bookIndexVOS);
    }

    @Override
    public void updateSaleCountPCS(Map<Long, Integer> bookPCSMap) {
        log.debug("开始更新 book表 销量和库存：【{}】", bookPCSMap);
        Set<Long> bookIds = bookPCSMap.keySet();
        for (Long bookId : bookIds) {
            if (bookMapper.updateSaleCountPCSById(bookId, bookPCSMap.get(bookId)) != 1) {
                log.warn("更新销量和库存时发生未知错误bookId：【{}】", bookId);
                throw new ServiceInternalException();
            }
        }
    }

    @Override
    public CommonResult<Void> multiDeleteByIds(Long[] ids) {
        int i = bookMapper.deleteBatchIds(Arrays.stream(ids).collect(Collectors.toList()));
        if (i != ids.length) {
            log.warn("根据ID数组批量删除图书数据时发生未知错误，ID数组：【{}】", Arrays.toString(ids));
            throw new ServiceInternalException();
        }
        return CommonResult.ok();
    }


    @Override
    public List<BookNameByKeyWordVO> getBookNameByBookName(String keyword) {
        log.debug("通过关键字【{}】搜索书名", keyword);

        String decode = null;
        try {
            decode = URLDecoder.decode(keyword, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.warn("转码时发生错误");
            e.printStackTrace();
            throw new ServiceInternalException();
        }
        if (decode == null) {
            log.debug("关键字为空结束方法");
            return null;
        }
        return bookMapper.selectBookNameByKeyword(decode);
    }

}




